<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="登录"
        @click-left="$router.go(-1)"
        left-arrow
      ></van-nav-bar>
    </header>
    <div class="content">
      <van-form validate-first @failed="onFailed" @submit="onSubmit">
        <!-- 验证手机号码 -->
        <van-field
          v-model="tel"
          name="tel"
          clearable
          placeholder="请输入手机号码"
          :rules="[{ required: true, pattern: pattern1, message: '请输入正确的手机号码' }]"
        />
        <van-field
          v-model="password"
          name="password"
          clearable
          placeholder="请输入密码"
          type="password"
          :rules="[{ required: true, pattern: pattern2, message: '密码长度不能少于6位' }]"
        />
        <div style="margin: 16px;">
          <van-button round block  color="pink" native-type="submit">
            登录
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { Button, NavBar, Form, Field, Toast } from 'vant'
import { login } from '@/api'
Vue.use(Button)
Vue.use(NavBar)
Vue.use(Form)
Vue.use(Field)
Vue.use(Toast)
export default {
  data () {
    return {
      tel: '13360321362',
      password: '123456',
      pattern1: /^1[3456789]\d{9}$/,
      pattern2: /\d{6}/
    }
  },
  methods: {
    onFailed (errorInfo) {
      console.log('errorInfo', errorInfo)
      Toast.fail(errorInfo.errors[0].message)
    },
    onSubmit () {
      console.log('登录')
      login({
        tel: this.tel,
        password: this.password
      }).then(res => {
        console.log(res.data)
        const { code } = res.data
        switch (code) {
          case '10400':
            Toast('信息填写不完整')
            break
          case '10888':
            Toast('登录成功')
            // 返回用户id、token、昵称 -- 保存在本地 - 返回上一页
            localStorage.setItem('userid', res.data.data.userid)
            localStorage.setItem('token', res.data.data.token)
            localStorage.setItem('nickname', res.data.data.nickname)
            // 给本地保存一个登录状态，用于前端校验
            // 加入购物车，获取本地loginState，如果未ok，进入服务器校验，如果不存在，不走服务器，直接进入登陆
            localStorage.setItem('loginState', 'ok')
            this.$router.go(-1)
            break
          case '10808':
            Toast('该用户未注册')
            break
          default:
            break
        }
      })
    }
  }
}
</script>
